package com.example.service.impl;

import com.example.entity.OutStore;
import com.example.entity.Product;
import com.example.entity.Result;
import com.example.mapper.OutStoreMapper;
import com.example.mapper.ProductMapper;
import com.example.page.Page;
import com.example.service.OutStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@Service
public class OutStoreServiceImpl implements OutStoreService {
    @Autowired
    private OutStoreMapper outStoreMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 添加出库单的业务方法
     * @param outStore
     * @return
     */
    @Transactional
    @Override
    public Result saveOutStore(OutStore outStore) {
        // 持久化添加的出库单
        if (outStoreMapper.insertOutStore(outStore) <= 0) { // 系统错误
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }
        return Result.ok("出库成功！");
    }

    /**
     * 根据条件查询出库单并分页的业务方法
     * @param outStore
     * @param page
     */
    @Override
    public void queryOutStoreByConditionForPagination(OutStore outStore, Page page) {
        //1 根据条件查询出库单的数量
        int outStoreCount = outStoreMapper.selectOutStoreCountByCondition(outStore);

        //2 根据条件查询分页后的出库单对象
        List<OutStore> outStoreList = outStoreMapper.selectOutStoreByConditionForPagination(outStore, page);

        //3 封装参数page对象
        page.setTotalNum(outStoreCount);
        page.setResultList(outStoreList);
    }

    /**
     * 根据出库单id确定出库
     * @param outStore
     * @return
     */
    @Override
    public Result confirmOutStoreIsOutById(OutStore outStore, Integer updateBy) {
        //1 查询出出库的商品并修改其库存
        Product product = productMapper.selectProductById(outStore.getProductId());
        // 修改内存中的商品对象的库存
        int prevent = product.getProductInvent() - outStore.getOutNum();// 剩余库存
        product.setProductInvent(prevent);
        product.setUpdateBy(updateBy);

        // 修改数据库中的商品库存
        if (productMapper.updateProductInventById(product) <= 0) {// 系统错误
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }

        //2 修改内存中出库单对象的信息并持久化
        BigDecimal outPrice = BigDecimal.valueOf(product.getSalePrice());
        outStore.setOutPrice(outPrice);

        if (outStoreMapper.updateOutStoreIsOutById(outStore) <= 0) {
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }

        return Result.ok("出库成功！");
    }


}
